import contextvars

from fastapi import Request

# 创建一个 context variable 来存储 Request 对象
request_context_var = contextvars.ContextVar("request")


def set_request_context(request: Request):
    request_context_var.set(request)


def get_request_context():
    return request_context_var.get()


async def add_request_context(request: Request, call_next):
    set_request_context(request)
    response = await call_next(request)
    return response
